package yunquan.wang.modules.base.service.impl;

import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import yunquan.wang.modules.base.entity.Report;
import yunquan.wang.modules.base.entity.Report.SqlType;
import yunquan.wang.modules.base.entity.ReportParameter;
import yunquan.wang.modules.base.service.JdbcOperationService;
import yunquan.wang.modules.base.service.ReportQueryService;
import yunquan.wang.modules.base.service.ReportService;

import com.google.common.collect.Maps;

public class ReportQueryServiceImpl implements ReportQueryService{
	ReportService reportService;
	JdbcOperationService jdbcOperationService;
	@Override
	public JasperPrint generateJasperPrint(String reportId,
			List<ReportParameter> parameters) {
		 Report report=reportService.get(reportId);
		JRDataSource dataSource=queryDataSource(report,getQueryParam(parameters));
		Map<String,Object> outParam=getOutParam(parameters);
		try {
			JasperReport jasperReport=	(JasperReport) JRLoader.loadObjectFromFile(report.getTemplatePath());
			return	 JasperFillManager.fillReport(jasperReport,outParam,dataSource);
		} catch (JRException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<ReportParameter> getReportParameters(String reportId) {
		// TODO  
		return null;
	}

	private Map<String,Object> getOutParam(List<ReportParameter> parameters)
	{
		Map<String,Object> paramMap=Maps.newHashMap();
		for(ReportParameter param:parameters)
		{
			//if is out
			paramMap.put(param.getName(), param.getValue());
		}
		return paramMap;
	}
	private Map<String,Object>  getQueryParam(List<ReportParameter> parameters)
	{
		Map<String,Object> paramMap=Maps.newHashMap();
		for(ReportParameter param:parameters)
		{
			//if is in
			paramMap.put(param.getName(), param.getValue());
		}
		return paramMap;
	}
	private JRDataSource queryDataSource(Report report,Map<String,Object> parameters)
	{
		if(report.getSqlType().equals(SqlType.SQL))
		{
		List<Map<String,?>> queryList=	jdbcOperationService.queryList(report.getSqlString(), parameters);
		return new JRMapCollectionDataSource(queryList);
		}
		return null;
	}
	
}
